@extends('layouts.base')

@section('title', '设备')

@section('admin-style')
<link rel="stylesheet" href="{{ asset('assets\element-ui\lib\theme-chalk\index.css') }}">
<!-- import Vue before Element -->
<script src="{{ asset('assets\vue\vue.js')}}"></script>

<!-- import JavaScript -->
<script src="{{ asset('assets\element-ui\lib\index.js') }}"></script>
<script src="{{ asset('assets\axios\axios.min.js') }}"></script>
<style>
	.el-input_inner {
		width:100%
	}

</style>
@stop



@section('content')

<!-- ============================================================== -->
<!-- Container fluid  -->
<!-- ============================================================== -->
<div class="container-fluid">
	<!-- ============================================================== -->
	<!-- Bread crumb and right sidebar toggle -->
	<!-- ============================================================== -->
	<div class="row page-titles">
	    <div class="col-md-5 align-self-center">
	        <h3 class="text-themecolor">设备--列表</h3>
	    </div>
	    <div class="col-md-7 align-self-center">
	        <ol class="breadcrumb">
	            <li class="breadcrumb-item"><a href="javascript:void(0)">首页</a></li>
	            <li class="breadcrumb-item">设备管理</li>
	            <li class="breadcrumb-item active">设备列表</li>
	        </ol>
	    </div>
	</div>
	<!-- ============================================================== -->
	<!-- End Bread crumb and right sidebar toggle -->
	<!-- ============================================================== -->

	<!-- ============================================================== -->
	<!-- Start Page Content -->
	<!-- ============================================================== -->
	<div class="row">
	    <div class="col-12">
	        <div class="card">
	            <div class="card-body">
	                <h4 class="card-title">管理列表</h4>
	                <h6 class="card-subtitle"></h6>
                	<div class="card-body">
						<el-form ref="formSearch" :inline="true" :model="formSearch" class="demo-form-inline">
							<el-form-item label="设备ID" v-if="type == 1">
							  <el-input v-model="formSearch.id" placeholder="设备ID"></el-input>
							</el-form-item>
							<el-form-item label="设备编号">
								<el-input v-model="formSearch.imei" placeholder="imei"></el-input>
							</el-form-item>
							<el-form-item label="经销商" v-if="type == 2 || type == 1">
								<el-select v-model="formSearch.broker" filterable  placeholder="经销商">
									<el-option v-for="(broker, index) in brokerList" :label="broker.name" :key="index" :value="broker.id.toString()"></el-option>
								</el-select>
							</el-form-item>
							<el-form-item label="商户">
								<el-select v-model="formSearch.merchant" filterable  placeholder="商户">
									<el-option v-for="(merchant, index) in merchantList" :label="merchant.name" :key="index" :value="merchant.id.toString()"></el-option>
								</el-select>
							</el-form-item>
							<el-form-item label="运维" v-if="type == 3 || type == 1">
								<el-select v-model="formSearch.operator" filterable  placeholder="运维">
									<el-option v-for="(operator, index) in operatorList" :label="operator.name" :key="index" :value="operator.id.toString()"></el-option>
								</el-select>
							</el-form-item>
							<el-form-item label="到期时间">
								<el-date-picker
									v-model="formSearch.expire_time"
									type="daterange"
									align="right"
									unlink-panels
									range-separator="至"
									start-placeholder="开始日期"
									end-placeholder="结束日期"
									value-format="yyyy-MM-dd"
									:picker-options="pickerOptions">
								</el-date-picker>
							</el-form-item>
							<el-form-item label="主板类型">
								<el-select v-model="formSearch.mainborad" filterable  placeholder="主板类型">
									<el-option v-for="(mainborad, index) in mainboradList" :label="mainborad.name" :key="index" :value="mainborad.id.toString()"></el-option>
								</el-select>
							</el-form-item>
							<el-form-item label="是否在线">
								<el-select v-model="formSearch.online" placeholder="是否在线">
									<el-option label="未启用" value="0"></el-option>
									<el-option label="上线" value="1"></el-option>
									<el-option label="离线" value="2"></el-option>
								</el-select>
							</el-form-item>
						</el-form>
                        <form method="get" action="{{ route('admin.machines.index') }}">
                            <div class="form-row">
								<div class="col-md-3 mb-3" v-if="type == 1">
									<input type="text" v-show="false" name="id" class="form-control" id="validationDefault04" placeholder="ID" :value="formSearch.id" >
								</div>
                                <div class="col-md-3 mb-3">
                                  <input type="text" v-show="false" name="imei" class="form-control" id="validationDefault04" placeholder="imei" :value="formSearch.imei" >
                                </div>
                                <div class="col-md-3 mb-3" v-if="type == 2 || type == 1">									
								    <input v-show="false" name="broker" :value="formSearch.broker">
                                </div>
                                <div class="col-md-3 mb-3">
								    <input v-show="false" name="merchant" :value="formSearch.merchant">
                                </div>
                                <div class="col-md-3 mb-3" v-if="type == 3 || type == 1">
								    <input v-show="false" name="operator" :value="formSearch.operator">
                                </div>
                                <div class="col-md-3 mb-3">
								    <input v-if="formSearch.expire_time != ''" v-show="false" name="expire_time" :value="formSearch.expire_time">
                                </div>
                                <div class="col-md-3 mb-3">
									<input v-show="false" name="mainborad" :value="formSearch.mainborad">
                                </div> 
                                <div class="col-md-3 mb-3">
									<input v-show="false" name="online" :value="formSearch.online">
                                </div>                               
                            </div>
                            <button class="btn btn-primary" type="submit">筛选</button>
                            <a href="{{ route('admin.machines.index') }}" class="btn btn-info">重置</a>
                            <a href="{{ route('admin.machines.index') }}" class="btn btn-warning">刷新</a>
                        </form>
                        <div class="row float-right">
                        	@can('admin.machines.bindOperator')
	                        <a href="javascript:;" @click="distributionDialog(4)" class="btn btn-success" style="margin-right:20px"><i class="fas fa-edit"></i> 运维分配设备</a>
	                        @endcan
							@if(auth('admin')->user()->can('admin.machines.bindMerchant') || auth('admin')->user()->id == 79)
	                        <a href="javascript:;" @click="distributionDialog(3)" class="btn btn-success" style="margin-right:20px"><i class="fas fa-edit"></i> 商户分配设备</a>
	                        @endif
                        	@can('admin.machines.bindBroker')
	                        <a href="javascript:;" @click="distributionDialog(2)" class="btn btn-success" style="margin-right:20px"><i class="fas fa-edit"></i> 经销商分配设备</a>
	                        @endcan	                        
	                        @can('admin.machines.create')
	                        <a class="btn btn-info" href="{{ route('admin.machines.create') }}"><i class="fas fa-plus"></i> 添加</a>
	                        @endcan
	                    </div>
                    </div>        
	                <div class="table-responsive">
	                    <table id="demo-foo-addrow" class="table table-bordered m-t-30 table-hover contact-list" data-paging="true" data-paging-size="7">
	                        <thead>
	                            <tr>
	                                <th>ID</th>
	                                <th>名称</th>
	                                <th>IMEI</th>
	                                <th>主板类型</th>
	                                <th>上级经销商</th>
	                                <th>商户</th>
	                                <th>运维</th>
	                                <th>信号值</th>
	                                <th>温度值</th>
	                                <th>照明状态</th>
	                                <th>温控状态</th>
	                                <th>到期时间</th>
	                                <th>状态</th>
	                                <th>上线时间</th>
	                                <th>操作</th>
	                            </tr>
	                        </thead>
	                        <tbody>
	                        	@foreach($machines as $value)
	                            <tr>
	                                <td>{{ $value->id }}</td>
	                                <td>{{ $value->name }}</td>
	                                <td><a class="text-{{ machine_state_class($value->online) }}" href="javascript:;" onclick="machineShow({{ $value->id }})">{{ $value->imei }}</a></td>
	                                <td>{{ optional($value->mainborad)->name }}</td>
	                                <td>{{ optional(optional($value->merchant)->parent)->name }}</td>
	                                <td>{{ optional($value->merchant)->name }}</td>
	                                <td>{{ optional($value->operator)->name }}</td>
	                                <td>{{ $value->signal}}</td>
	                                <td>{{ $value->tem}}</td>
	                                <td>{{ led_state($value->led_state) }}</td>
	                                <td>{{ tem_state($value->tem_state) }}</td>
	                                <td><span @if(is_expire_time($value->expire_time) == '过期')class="text-danger"@endif>{{ is_expire_time($value->expire_time) }}</span></td>
	                                <td><span class="text-{{ machine_state_class($value->online) }}">{{ machine_state($value->online) }}</span></td>
	                                <td>{{ $value->connected_at }}</td>
	                                <td>{!! $value->actionButton !!}</td>
	                            </tr>
	                            @endforeach
	                        </tbody>
	                    </table>
	                    {{ $machines->appends($query)->links() }}
	                </div>
	                <el-dialog :before-close="handleClose" title="分配设备" :visible.sync="dialogFormDistribution">
					  <el-form style="margin: 10px 110px;" label-position="right" label-width="150px" :rules="machineRules" ref="machineForm" :model="machineForm" >
					    <el-form-item label="设备编号" prop="imei">
					      <el-input :autosize="{ minRows: 5, maxRows: 20}" style="width: 90%;" placeholder="请输入正确的设备IMEI号,以回车隔开" type="textarea" v-model="machineForm.imei" autocomplete="off"></el-input>
					    </el-form-item>
					    <el-form-item label="分配人" prop="manager_id">
					      <el-select style="width: 90%;" filterable v-model="machineForm.manager_id" placeholder="请选择分配人">
					        <el-option v-for="item in managerList"
						      :key="item.id"
						      :label="item.name"
						      :value="item.id">@{{item.name + '--('+ item.role_name +')'}}</el-option>	
					      </el-select>
					    </el-form-item>
					  </el-form>
					  <div slot="footer" class="dialog-footer">
					    <el-button @click="disdistribution('machineForm')">取 消</el-button>
					    <el-button type="primary" @click="distribution">确 定</el-button>
					  </div>
					</el-dialog>
	            </div>
	        </div>
	    </div>
	</div>
</div>         
                        
@stop

@section('admin-js')
	<script type="text/javascript">		
		Vue.prototype.$axios = axios;
	    Vue.prototype.$dcopy = function($arr){
	        return JSON.parse(JSON.stringify($arr));
	    }
		function machineShow($id){
			var state = "{{ auth('admin')->user()->can('admin.machines.show') }}";
			if(state){
				location.href = "/admin/machines/"+$id
			}else{
				swal({
				  title: "您没有详情访问权限",
				  icon: "warning",
				  buttons: '确定',
				});
			}
		}
		new Vue({
			el: '#app',
			data: function(){
				var time = "{{ $query['expire_time'] }}";
				if(time){
					var time = JSON.stringify("{{ $query['expire_time'] }}").split(',');
				}
				return {
					formSearch: {
						id: "{{ $query['id'] }}" || '',
						imei: "{{ $query['imei'] }}" || '',
						broker:"{{ $query['broker'] }}" || '',
						merchant:"{{ $query['merchant'] }}" || '',
						operator:"{{ $query['operator'] }}" || '',
						mainborad:"{{ $query['mainborad'] }}" || '',
						online:"{{ $query['online'] }}" || '',									        
						expire_time:time,
					},
					dialogFormDistribution:false,
					type: "{{ auth('admin')->user()->type }}",
					pickerOptions: {
			          shortcuts: [{
			            text: '最近一周',
			            onClick(picker) {
			              const end = new Date();
			              const start = new Date();
			              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
			              picker.$emit('pick', [start, end]);
			            }
			          }, {
			            text: '最近一个月',
			            onClick(picker) {
			              const end = new Date();
			              const start = new Date();
			              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
			              picker.$emit('pick', [start, end]);
			            }
			          }, {
			            text: '最近三个月',
			            onClick(picker) {
			              const end = new Date();
			              const start = new Date();
			              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
			              picker.$emit('pick', [start, end]);
			            }
			          }]
			        },
			        machineForm:{
			        	imei:'',
			        	manager_id:'',
			        	type:'',
			        },
			        machineRules:{
			        	imei: [
	                        { required: true, message: '请输入设备编号', trigger: 'blur' },
	                    ],
	                    manager_id:[
	                    	{ required: true, message: '请选择分配人', trigger: 'change'}
	                    ]
			        },
			        managerList:[],
					brokerList:[],
					mainboradList:[],
					operatorList:[],
					merchantList:[],
				}	
			},
			mounted:function(){
				this.loadBrokers();
				this.loadMainborads();
				this.loadMerchants();
				this.loadOperators();
			},
			methods:{
				del(id){
            		var that = this;
            		swal({
					  title: "您确定要删除吗?",
					  icon: "warning",
					  buttons: ['取消', '确定'],
					  dangerMode: true,
					})
					.then((willDelete) => {
					  if (willDelete) {			    
					    axios.post("{{ route('admin.machines.delete') }}",{'id':id})
					    .then(res => {
					    	if(res.data.code == 400){
					    		that.$message.error(res.data.message);
					    	}
					    	if(res.data.code == 200){
					    		that.$message.success(res.data.message);
					    		location.href = "{{ route('admin.machines.index') }}"
					    	}
					    });
					  } else {
					    
					  }
					});
            	},
            	distributionDialog(type){
            		var that = this;
            		that.dialogFormDistribution = true;
            		that.machineForm.type =type;
            		axios.get("{{ route('admin.machines.getChildrenAll') }}",{
            			params:{
            				type:type
            			}
            		})
            		.then(res => {
            			that.managerList = res.data.data;
            		});
            	},
            	distribution(){
            		var that = this;
            		axios.post("{{ route('admin.machines.bindMachines') }}",that.machineForm).
            		then(res => {
            			that.dialogFormDistribution = false;
            			that.$refs.machineForm.resetFields();
            			setTimeout(function(){
            				location.href = "{{ route('admin.machines.index') }}"
            			},1000)
            			that.$message.success('绑定成功');
           				if(res.data.error){
           					for (var i = 0; i <= res.data.error.length; i++) {
           						that.$notify.error({
           							title: '错误',
          							message: 'imei:' + res.data.error[i].imei + res.data.error[i].error,
          							duration: 5000	
           						});
           					}           					
           				}

            		});
            	},
            	disdistribution(formName){
            		var that = this;
            		that.$refs[formName].resetFields();
            		that.dialogFormDistribution = false;

            	},
            	handleClose(){
            		var that = this;
            		that.$refs.machineForm.resetFields();
            		that.dialogFormDistribution = false;
            	},
            	resetMachine(id){
            		var that = this;
            		swal({
					  title: "您确定要初始化设备吗?",
					  icon: "warning",
					  buttons: ['取消', '确定'],
					  dangerMode: true,
					})
					.then((willDelete) => {
					  	if (willDelete) {			
		            		axios.post("{{ route('admin.machines.resetMachine') }}",{
		            				id:id
		            			})
		            		.then(res => {
						    	if(res.data.code == 200){
						    		that.$message.success('重置成功');				    		
						    	}
						    	location.href = "{{ route('admin.machines.index') }}"
		            		});
            			} 
					});
            	},
				loadBrokers(){
					var that = this;
					axios.get("{{ route('admin.brokers.lists') }}")
					.then(res => {
						this.brokerList = res.data.data;
					});
				},
				loadMainborads(){
					var that = this;
					axios.get("{{ route('admin.mainborads.lists') }}")
					.then(res => {
						this.mainboradList = res.data.data;
					});
				},
				loadMerchants(){
					var that = this
					axios.get("{{ route('admin.merchants.lists') }}")
					.then(res => {
						this.merchantList = res.data.data;
					});
				},
				loadOperators(){
					var that = this
					axios.get("{{ route('admin.operators.lists') }}")
					.then(res => {
						this.operatorList = res.data.data;
					});
				}
			}
		});
		
	</script>

@stop